package sc;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Information extends Object
{
	public static boolean firstUpdate = true;

	public boolean serverStatusPlayer;
	public boolean serverStatusGMs;
	public boolean serverStatusMasterGMs;
	public boolean serverStatusAdmins;

	private static String fetcheddata;
	private static Member member;
	private static String myipaddress = null;

	private List<Member> onForum = new ArrayList<Member>();
	private List<Member> inChat = new ArrayList<Member>();
	private List<Member> inVent = new ArrayList<Member>();
	private URL venturl;
	private URL staticurl;
	private URL dynamicurl;
	private URL wimiurl;
	private URLConnection conn;
	private int totalOnForum;
	private int totalInChatroom;
	private int totalInVent;
	private String[] info;

	public Information()
	{
		try
		{
			venturl = new URL(
					"http://www.nanospy.de/track.php?ip=harlequin.servegame.com&port=4328&prot=ventrilo");
			staticurl = new URL(
					"http://www.theharlequin.com.au/sysbox/static.php");
			dynamicurl = new URL(
					"http://www.theharlequin.com.au/sysbox/dynamic.php");
			wimiurl = new URL("http://whatismyip.com/automation/n09230945.asp");
		} catch (MalformedURLException e)
		{
		}

		totalOnForum = 0;
		totalInChatroom = 0;
		totalInVent = 0;

		myipaddress = fetchURL(wimiurl).trim();
	}

	public void update()
	{
		totalOnForum = 0;
		totalInChatroom = 0;
		totalInVent = 0;

		onForum.clear();
		inChat.clear();
		inVent.clear();

		for (Member member : Member.getAllMembers())
		{
			if (member.onForum())
				onForum.add(member);
			if (member.inChat())
				inChat.add(member);
			if (member.inVent())
				inVent.add(member);
		}

		fetcheddata = fetchURL(dynamicurl);

		if (fetcheddata != null && fetcheddata.startsWith("CTA:"))
			CallToArms.open(fetcheddata);

		else if (fetcheddata != null)
		{
			int pos = 0;

			while (pos < fetcheddata.length() - 1)
			{
				String member_id = "";
				char ch = fetcheddata.charAt(pos);
				while (ch != 'B' && ch != 'F' && ch != 'C')
				{
					member_id += ch;
					ch = fetcheddata.charAt(++pos);
				}
				try
				{
					member_id = Integer.toString(Integer
							.parseInt(member_id, 16));
				} catch (NumberFormatException e)
				{
					continue;
				}
				member = Member.getMemberByID(member_id);
				if (member == null)
				{
					updateKnownMembers();
					member = Member.getMemberByID(member_id);
				}
				if (member != null)
				{
					if (ch == 'B' || ch == 'F')
					{
						totalOnForum++;
						member.onForum(true);
						onForum.remove(member);
					}
					if (ch == 'B' || ch == 'C')
					{
						totalInChatroom++;
						member.inChat(true);
						inChat.remove(member);
					}
				}

				pos++;
			}

			for (Member member : onForum)
				member.onForum(false);
			for (Member member : inChat)
				member.inChat(false);

		}

		if ((fetcheddata = fetchURL(venturl)) != null)
		{
			for (String line : fetcheddata.split("<a href=\"#\" "))
			{
				int titlepos = line.indexOf("title=\"Ping: ");
				if (titlepos > -1)
				{
					int connectedpos = line.indexOf(", Connected: ");
					int namepos = line.indexOf("\">");
					int nameend = line.indexOf("</a>");
					String ping = line.substring(titlepos + 13, connectedpos);
					String time = line.substring(connectedpos + 13, namepos);
					String name = line.substring(namepos + 2, nameend);
					Member member = Member.getMemberByName(name, false);
					if (member != null)
					{
						member.inVent(true);
						member.ventInfo(time, ping);
						inVent.remove(member);
						totalInVent++;
					}
				}
			}
		}

		for (Member member : inVent)
			member.inVent(false);

		for (Member member : Member.getAllMembers())
		{
			String ip = member.getIP();
			if (ip != null && ip.equals(myipaddress))
				member.isUser(true);
		}

		for (Member member : Member.getAllMembers())
		{
			String ip = member.getIP();
			if (ip != null && ip.equals(myipaddress) && member.online())
				member.isUser(true);
		}

		updateTooltip();

		if (firstUpdate)
		{
			Tray.event(totalOnForum() + " forum, " + totalInChatroom()
					+ " chat, " + totalInVent() + " vent");
			firstUpdate = false;

			if (Configuration.startupMembersList())
				Harlequin.getInstance().setVisible(true);
		}
	}

	private void updateKnownMembers()
	{
		String websitedata;

		if ((websitedata = fetchURL(staticurl)) == null)
			return;

		for (String line : websitedata.split("\n"))
		{
			info = line.split(",");
			if (info.length < 8)
				continue;
			String name = info[1].replaceAll("&.*;", "");
			Member member = Member.getMemberByName(name, true);
			member.setMemberId(Integer.toString(Integer.parseInt(info[0], 16)));
			member.setRank(info[3]);
			member.setRace(info[4]);
			member.setSex(info[5]);
			member.setIP(info[6]);
			if (myipaddress != null && myipaddress.equals(info[7]))
				member.setIP(info[7]);
			if (info.length > 8)
				member.setAward(info[8]);
			member.updateSortValue();
		}
	}
		
	private void updateTooltip()
	{
		String tooltip = "Harlequin SysBox\n\n";
		tooltip += totalOnForum() + " on forum\n";
		tooltip += totalInChatroom()+ " in chat\n";
		tooltip += totalInVent() + " in vent\n\n";
		Tray.setToolTip(tooltip);
	}

	private String fetchURL(URL url)
	{
		String result = "";
		try
		{
			conn = url.openConnection();
			Scanner scanner = new Scanner(conn.getInputStream());
			while (scanner.hasNext())
				result += scanner.nextLine() + '\n';
		} catch (IOException ex)
		{
			Log.info(ex.getLocalizedMessage());
		}
		return result;
	}

	public int totalInChatroom()
	{
		return totalInChatroom;
	}

	public int totalInVent()
	{
		return totalInVent;
	}

	public int totalOnForum()
	{
		return totalOnForum;
	}

}
